<template>

<t-tabs value="first" theme="normal" @add="addItem" :addable="true">
  <t-tab-panel value="first">
      <template #label> <t-icon name="home" class="tabs-icon-margin" /> 传感器 </template>
      <div style="padding: 2px;">
        <t-table
          ref="tableRef"
          row-key="key"
          :columns="columns"
          :data="data"
          :editable-row-keys="editableRowKeys"
          table-layout="auto"
          size="small"
          bordered
          lazy-load
          @row-edit="onRowEdit"
          @row-validate="onRowValidate">
        
          <template #operation="{ row }">
            <t-space>
            <t-link theme="primary" hover="color" :data-id="row.key" @Click="onEdit" v-show="!editableRowKeys.includes(row.key)">
                编辑
              </t-link>

              <t-link theme="error" hover="color" :data-id="row.key" @Click="onDel" v-show="!editableRowKeys.includes(row.key)">
                删除
              </t-link>
              <t-link theme="primary" hover="color" :data-id="row.key" @Click="onSave" v-show="editableRowKeys.includes(row.key)">
                保存
              </t-link>
              <t-link theme="primary" hover="color" :data-id="row.key" @Click="onCancel" v-show="editableRowKeys.includes(row.key)">
                取消
              </t-link>
            </t-space>
          </template>
        </t-table>
         
      </div>
  </t-tab-panel>
</t-tabs>
<AddModbus ref="modbus" @query="getDataList"></AddModbus>
</template>
<script setup name="modbus">
import { Input, Select, InputNumber, MessagePlugin } from 'tdesign-vue-next';
import AddModbus from './AddModbus.vue';
import {ref,computed} from 'vue';
import { getProductProfile,delProductProfile } from '@/api/api';
const {type,product} = defineProps(['type','product'])

const tableRef = ref();
const modbus = ref();
const currentSaveId = ref('');
const data = ref([])
const editableRowKeys = ref([]);


const getDataList = () => {
  console.log('zhixingle')
  let params = {
    product:product,
    type:type,
  }
  getProductProfile(params).then(res=>{
    if(res.code === 200) {
      console.log(res.data)
      for(let i=0;i<res.data.length;i++ ) {

        let m = {}

        for(let j = 0;j<res.data[i].profile.length;j++){
          m[res.data[i].profile[j].Key] = res.data[i].profile[j].Value
        }
       
       m["key"] = res.data[i].key
      
       data.value.push(m)
       
      }
      
      console.log(data.value)
    }
  })
}

const addItem = () => {
  let row = {
    'type':type,
    'product':product
  }
  modbus.value.open(row)
}
// 保存变化过的行信息
const editMap = {};

const updateEditState = (id) => {
  const index = editableRowKeys.value.findIndex((t) => t === id);
  editableRowKeys.value.splice(index, 1);
};

const onEdit = (e) => {
  const { id } = e.currentTarget.dataset;
  console.log(e)
  if (!editableRowKeys.value.includes(id)) {
    editableRowKeys.value.push(id);
    console.log(editableRowKeys.value)
  }
};


const onDel = (e) => {
  const { id } = e.currentTarget.dataset;
  console.log(e)
  if (editableRowKeys.value.includes(id)) {
    let params = {
      "key":id
    }
    delProductProfile(params).then(res=>{
      if(res.code === 200) {
        updateEditState(id);
        tableRef.value.clearValidateData();
        const index = data.value.findIndex((item)=>item.key===id);
        data.value.splice(index,1);
        console.log(editableRowKeys.value)
      }
    })
    
  }
}

const onCancel = (e) => {
  console.log(e)
  const { id } = e.currentTarget.dataset;
  updateEditState(id);
  tableRef.value.clearValidateData();
};



const onSave = (e) => {
  const { id } = e.currentTarget.dataset;
  currentSaveId.value = id;
  // 触发内部校验，而后也可在 onRowValidate 中接收异步校验结果
  tableRef.value.validateRowData(id).then((params) => {
  
    if (params.result.length) {
      const r = params.result[0];
      MessagePlugin.error(`${r.col.title} ${r.errorList[0].message}`);
      return;
    }
    // 如果是 table 的父组件主动触发校验
    if (params.trigger === 'parent' && !params.result.length) {
      const current = editMap[currentSaveId.value];
      if (current) {
        console.log(current)
        data.value.splice(current.rowIndex, 1, current.editedRow);
        MessagePlugin.success('保存成功');
      }
      updateEditState(currentSaveId.value);
    }
  });
};

const onRowValidate = (params) => {
  console.log('Event Table Row Validate:', params);
};

const onRowEdit = (params) => {
  const { row, col, value } = params;
  const oldRowData = editMap[row.key]?.editedRow || row;
  const editedRow = { ...oldRowData, [col.colKey]: value };
  editMap[row.key] = {
    ...params,
    editedRow,
  };}


  const CODE_OPTIONS = [
  { label: '读线圈状态', value: 1 },
  { label: '读离散输入', value: 2 },
  { label: '读保持寄存器', value: 3 },
  { label: '读输入寄存器', value: 4 },
];


const columns = computed(() => [
  {
    title: '名称',
    colKey: 'name',
    width: 120,
    // 编辑状态相关配置，全部集中在 edit
    edit: {
      // 1. 支持任意组件。需保证组件包含 `value` 和 `onChange` 两个属性，且 onChange 的第一个参数值为 new value。
      // 2. 如果希望支持校验，组件还需包含 `status` 和 `tips` 属性。具体 API 含义参考 Input 组件
      component: Input,
      // props, 透传全部属性到 Input 组件
      props: {
        clearable: true,
        autofocus: true,
        autoWidth: true,
      },
      // 校验规则，此处同 Form 表单
      rules: [
        { required: true, message: '不能为空' },
      ],
      showEditIcon: false,
    },
  },
  {
    title: '功能码',
    colKey: 'code',
    cell: (h, { row }) => CODE_OPTIONS.find((t) => t.value === row.code)?.label,
    edit: {
      component: Select,
      // props, 透传全部属性到 Select 组件
      props: {
        clearable: true,
        autoWidth: true,
        options: CODE_OPTIONS,
      },
      // 校验规则，此处同 Form 表单
      rules: [{ required: true, message: '不能为空' }],
      showEditIcon: false,
      on: ({ updateEditedCellValue }) => ({
        onChange: () => {
          /**
           * change other columns edited cell value
           * 更新本行其他编辑态单元格的数据(to update editedRow)
           */
          updateEditedCellValue({
            isUpdateCurrentRow: true,
            letters: [],
            // 'user.firstName': '',
            // createTime: dayjs().add(1, 'day').toDate(),
          });
          /**
           * update edited row data with row unique value is qual to 2
           * 更新行唯一标识值为 2 的编辑态数据
           */
          // updateEditedCellValue({ rowValue: 2, letters: [] });
        },
      }),
    },
  },
  {
    title: '从站',
    colKey: 'station',
    edit: {
      component: InputNumber,
      props: {
        autofocus: true,
        autoWidth: true,
        theme:"column",
        min:1,
      },
      showEditIcon: false,
    },
  },
  {
    title: '起始地址',
    colKey: 'address',
    edit: {
      component: InputNumber,
      props: {
        autofocus: true,
        autoWidth: true,
        theme:"column",
        min:0,
      },
      showEditIcon: false,
    },
  },
  {
    title: '数量',
    colKey: 'num',
    edit: {
      component: InputNumber,
      props: { 
        autofocus: true,
        autoWidth: true,
        theme:"column",
        min:1,
       },
      showEditIcon: false,
    },
  },
  {
    title: '单位',
    colKey: 'unit',
    edit: {
      component: Input,
      props: {
        clearable: true,
        autofocus: true,
        autoWidth: true,
      },
      showEditIcon: false,
    },
  },
  {
    title: '系数',
    colKey: 'scale',
    edit: {
      component: InputNumber,
      props: { 
        autofocus: true,
        autoWidth: true,
        theme:"normal",
        min:0.0001,
       },
      showEditIcon: false,
    },
  },
  {
    title: '操作栏',
    colKey: 'operation',
    width: 150,
  },
]);
</script>